import {ValidateCredentials} from "~/lib/server";


export async function signin(username: string, password: string) {
    try {
        const data = await ValidateCredentials({"name": username, "password": password});
        const expiresAT = new Date(new Date().getTime() + data.expiresIn * 1000);
        localStorage.setItem('idToken', data.idToken);
        localStorage.setItem("expiresAt", expiresAT.toString());
    } catch (error) {
        throw new Error(`HTTP error: Status ${error}`);
    }
}

export function isLoggedIn() {

    const expiration = localStorage.getItem("expiresAt") || "";

    const expiresAt = new Date(expiration);
    if (isNaN(expiresAt.getTime())) {
        return false;
    }

    return Date.now() < expiresAt.getTime();


}

export async function signout() {

    localStorage.removeItem("idToken");
    localStorage.removeItem("expiresAt");


}